package com.example.warehouse.service.serviceImpl;

import com.example.warehouse.entity.ProductType;
import com.example.warehouse.entity.Result;
import com.example.warehouse.mapper.ProductTypeMapper;
import com.example.warehouse.service.ProductTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@CacheConfig(cacheNames ="com.example.warehouse.service.serviceImpl.ProductTypeServiceImpl" )
public class ProductTypeServiceImpl implements ProductTypeService{
    @Autowired
    private ProductTypeMapper productTypeMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    @Cacheable(key = "'all:Type'")
    public List<ProductType> findTypeTree() {
        List<ProductType> typeTree = productTypeMapper.findTypeTree();
        List<ProductType> allTypeTree = allTypeTree(typeTree, 0);
        return allTypeTree;
    }

    @Override
    public Result queryTypeByCode(String typeCode) {
        ProductType productType = productTypeMapper.findTypeByCode(typeCode);
        return Result.ok(productType==null);
    }

    @Override
    public void addType(ProductType productType) {
        productTypeMapper.addType(productType);
    }

    @Override
    public void deleteTypeById(Integer ids) {
        productTypeMapper.deleteById(ids);
    }

    @Override
    public void updateType(ProductType productType) {
        productTypeMapper.updateType(productType);
    }


    private List<ProductType> allTypeTree(List<ProductType> typeList,Integer pid){
        List<ProductType> firstLevelType=new ArrayList<>();
        for(ProductType productType: typeList){
            if(productType.getParentId().equals(pid)){
                firstLevelType.add(productType);
            }
        }
        for(ProductType productType:firstLevelType){
            List<ProductType> productTypes = allTypeTree(typeList, productType.getTypeId());
            productType.setChildProductCategory(productTypes);

        }
        return firstLevelType;
    }
}
